<template>
  <!-- 新播放器 -->
  <div class="app-new-player">
    <!-- 歌曲封面 名字 歌手 -->
    <div class="player-describe">
      <!-- 封面 -->
      <div class="player-song-pic">
        <img :src="musicInfoData.al.picUrl" />
        <!-- 鼠标移入 -->
        <div class="pic-shade">
          <van-icon name="arrow-up" />
        </div>
      </div>
      <!-- 名字 歌手-->
      <div class="player-name">
        <!-- 歌曲名 -->
        <div class="name-song">
          <span :title="musicInfoData.name">{{ musicInfoData.name }}</span>
          <van-icon
            name="like-o"
            v-if="userLoveList.indexOf(musicInfoData.id) == -1"
            @click="addMyLove(musicInfoData.id, 'true')"
          />
          <van-icon
            name="like"
            v-else
            class="user-love"
            @click="addMyLove(musicInfoData.id, 'false')"
          />
        </div>
        <!-- 歌手名 -->
        <div class="name-singer">
          <span>{{ musicInfoData.ar[0].name }}</span>
          <span v-if="musicInfoData.ar[1]"
            >/{{ musicInfoData.ar[1].name }}</span
          >
        </div>
      </div>
    </div>
    <!-- 播放控件 -->
    <div class="player-module">
      <!-- 真正的播放器 -->
      <audio
        :src="musicPlayUrl"
        :loop="musicPattern == false"
        ref="playAudio"
        :autoplay="isAutoplay"
      ></audio>
      <!-- 播放操作 -->
      <div class="player-module-operation">
        <!-- 默认顺序播放 -->
        <div :title="patternTitle" @click="setPattern">
          <i
            class="iconfont icon-liebiaoshunxu"
            v-if="musicPattern == true"
          ></i>
          <i class="iconfont icon-danquxunhuan" v-else></i>
        </div>
        <!-- 上一首 -->
        <div class="player-up" title="上一首" @click="cutMusic('up')">
          <i class="iconfont icon-diyiyeshouyeshangyishou"></i>
        </div>
        <!-- 播放/暂停 -->
        <div class="module-on-off" @click="playOnOff">
          <i
            class="iconfont icon-bofang"
            v-if="playOrOut == false"
            title="播放"
          ></i>
          <i class="iconfont icon-zanting" v-else title="暂停"></i>
        </div>
        <!-- 下一首 -->
        <div class="player-next" title="下一首" @click="cutMusic('next')">
          <i class="iconfont icon-zuihouyiyemoyexiayishou"></i>
        </div>
        <!-- 歌词 -->
        <div class="player-lyrice" title="打开歌词" @click="Toast(`打打打 打不开啊`)">
          <span>词</span>
        </div>
      </div>
      <!-- 播放进度条 -->
      <div class="player-progress-box">
        <!-- 开始时间 -->
        <span>{{ formatDate(new Date(playerPlan), "mm:ss") }}</span>
        <van-progress
          pivot-text=""
          color="#ff4e4e"
          track-color="#cdcdcd"
          :percentage="playRateOfProgress(playerPlan, sumPlan)"
          class="player-progress"
          @click="setPlayLong($event)"
        />
        <!-- 完整时间 -->
        <span>{{ formatDate(new Date(musicInfoData.dt), "mm:ss") }}</span>
      </div>
    </div>
    <!-- 附加选项 -->
    <div class="player-addition">
      <!-- 音质 -->
      <div
        class="player-tone-quality"
        @click="Toast(`作者送福利 码率都调最高了`)"
      >
        <span>极高</span>
      </div>
      <!-- 音量 -->
      <div class="player-volume">
        <!-- 音量分四个挡位 -->
        <i class="iconfont icon-jingyin" v-if="audioVolume == 0"></i>
        <i
          class="iconfont icon-24gl-volumeLow"
          v-if="audioVolume >= 0.1 && audioVolume <= 0.3"
        ></i>
        <i
          class="iconfont icon-24gl-volumeMiddle"
          v-if="audioVolume >= 0.4 && audioVolume <= 0.6"
        ></i>
        <i class="iconfont icon-24gl-volumeHigh" v-if="audioVolume >= 0.7"></i>
        <!-- 调节器 -->
        <div class="volume-change">
          <van-progress
            pivot-text=""
            color="#ff4e4e"
            track-color="#cdcdcd"
            :percentage="audioProgress"
            class="volume-changer-progress"
            @click="setPageVolume($event)"
          />
        </div>
      </div>
      <!-- 好友 -->
      <div class="player-friend" @click="Toast(`这个功能没啥用 不做了`)">
        <i class="iconfont icon-haoyou"></i>
      </div>
      <!-- 播放列表 -->
      <div class="player-playlist" @click="isShowPlayerSongList()">
        <i class="iconfont icon-24gf-playlist3"></i>
      </div>
    </div>
  </div>
  <player-song-list-vue
    :playerSongListIsShow="playerSongListIsShow"
    :playOrOut="playOrOut"
  ></player-song-list-vue>
</template>

<script setup>
import { ref, watch, computed } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import axios from "axios";
import { formatDate } from "../../hook/formatTime";
import playerSongListVue from "./playerSongList.vue";
import { Toast } from "vant";

const store = useStore();
const router = useRouter();

// 控制是否显示
const playerSongListIsShow = ref(false);
const isShowPlayerSongList = () => {
  playerSongListIsShow.value = !playerSongListIsShow.value;
};

// 时间戳
const nowTime = new Date().getTime();

store.dispatch("getMusicInfoData");
// 歌曲Id
const storeMuisc = computed(() => {
  return store.state.musicSrc;
});

// 歌曲详情
const musicInfoData = computed(() => {
  return store.state.musicInfo;
});

// 歌曲是否是用户喜欢歌曲
const userLoveList = computed(() => {
  return store.state.m_user.userSongLoveList;
});

const musicPlayUrl = ref("");
// 获取歌曲播放url
const getMusicPlayUrl = async (id) => {
  // 传递id 防止后续传参延迟
  await axios
    .get(`http://localhost:3000/song/url?id=${id || musicInfoData.value.id}`)
    .then((res) => {
      musicPlayUrl.value = res.data.data[0].url;
    })
    .catch((err) => {
      console.log("获取歌曲播放链接失败" + err);
    });
};
getMusicPlayUrl();
// 播放秒数
const playerPlan = ref(0);

// 歌曲秒数
const sumPlan = ref(musicInfoData.value.dt);
// 播放进度
const playRateOfProgress = (star, end) => {
  if (star == 0) return 0;
  console.log((star * 1000) / end / 10);
  // 当一首歌播放完毕时
  if ((star * 1000) / end / 10 >= 100) {
    // 重置播放器
    resetPlayer();
    if (musicPattern.value == true) {
      // 如果播放模式为顺序播放 则切换下一首
      console.log("顺序播放切换下一首");
      cutMusic("next");
      // 初始化播放器
      startPlayer();
      // 开始播放
      playAudio.value.play();
    } else {
      // 如果为单曲循环重新初始化播放器
      startPlayer();
    }
    return 0;
  }
  return (star * 1000) / end / 10;
};

// 播放器实例
const playAudio = ref(null);

// 播放或暂停的标志
const playOrOut = ref(false);

// 自动播放 默认不播放(浏览器限制)
const isAutoplay = ref(false);

// 定义定时器
let timer = null;

// 重置播放器时间 按钮 定时器
const resetPlayer = () => {
  // 关闭定时器
  clearInterval(timer);
  // 播放秒数清零
  playerPlan.value = 0;
  // 更改播放变量
  playOrOut.value = false;
};

// 开始播放器
const startPlayer = () => {
  // 更改播放变量
  playOrOut.value = true;
  // 播放秒数清零
  playerPlan.value = 0;
  // 开始播放
  playAudio.value.play();
  timer = setInterval(() => {
    playerPlan.value += 1000;
  }, 1000);
};

// 监听歌曲id更改
watch(
  () => storeMuisc.value,
  (newV) => {
    store.dispatch("getMusicInfoData", newV);
    // 获取新的歌曲 url
    getMusicPlayUrl(newV);
    if (isAutoplay.value == true) {
      // 重置播放器
      resetPlayer();
      // 开始播放
      startPlayer();
    } else {
      // 重置播放器
      resetPlayer();
    }
  },
  { deep: true, immediate: true }
);

// 监听歌曲长度更改
watch(
  () => store.state.musicInfo.dt,
  (newV) => {
    sumPlan.value = newV;
  },
  { deep: true }
);

// 播放或是暂停
const playOnOff = () => {
  // 当手动点击一次播放之后
  isAutoplay.value = true;
  playOrOut.value = !playOrOut.value;
  // 当开始播放时
  if (playOrOut.value == false) {
    // 暂停播放
    playAudio.value.pause();
    // 清除定时器
    clearInterval(timer);
  } else {
    try {
      // 没有异常开始播放
      playAudio.value.play();
      timer = setInterval(() => {
        playerPlan.value += 1000;
      }, 1000);
    } catch (error) {
      Toast(error);
      // 暂停播放
      playAudio.value.pause();
      // 清除定时器
      clearInterval(timer);
    }
  }
};

// 切换上一首下一首
const cutMusic = (str) => {
  /**
   * 查找出当前播放的歌曲在列表里的下标
   * str 为 up -1 next 则 +1
   * 做一下边界判断
   */
  // 在列表中的位置
  let index = store.state.m_song.songListData.findIndex((item) => {
    return item.id == storeMuisc.value;
  });

  // 如果查找不到就从列表第一首开始
  if (index == -1) return store.commit("updateMusicSrc", 0);

  // 如果是切换上一首
  if (str == "up") {
    // 如果下标为0或者等于数组的长度 表示在边界
    if (index == 0) return Toast("当前已经是第一首了");
    // 修改歌曲 id 为上一首
    return store.commit(
      "updateMusicSrc",
      store.state.m_song.songListData[index - 1].id
    );
  } else {
    if (index == store.state.m_song.songListData.length - 1)
      return Toast("已经是最后一首了");
    return store.commit(
      "updateMusicSrc",
      store.state.m_song.songListData[index + 1].id
    );
  }
};

// 收藏音乐
const addMyLove = (id, flag) => {
  axios
    .post(
      `/like?id=${id}&like=${flag}&cookie=${store.state.m_user.cookie}&timestamp=${nowTime}`
    )
    .then((res) => {
      if (!res) return Toast("服务器错误");
      if (flag == "false") {
        Toast("取消喜欢成功 ~");
      } else {
        Toast("已添加到我喜欢的音乐 ~ ");
      }
      // 刷新空白路由更新数据
      router.push({
        name: "refresh",
      });
    })
    .catch((err) => {
      console.error(err);
    });
};

// 循环模式 (默认单曲循环 防止服务器请求频繁)
const musicPattern = ref(false);
// 模式标题 title
const patternTitle = ref("循环播放");
// 切换循环模式
const setPattern = () => {
  musicPattern.value = !musicPattern.value;
  if (musicPattern.value == true) {
    Toast("已切换到顺序播放模式");
    return (patternTitle.value = "顺序播放");
  }
  patternTitle.value = "循环播放";
  return Toast("已切换到单曲循环模式");
};

// 点击播放滚动条事件 (快进后退)
const setPlayLong = (e) => {
  // 获取点击百分比
  const cilckLength = Math.round((e.offsetX * 100) / 370) / 100;
  // 进度条数值乘以百分比 (进度条百分比是参照播放时长 所以只修改播放时长即可)
  playerPlan.value = sumPlan.value * cilckLength;
  playAudio.value.currentTime = (sumPlan.value * cilckLength) / 1000;
};

// 音量变量(控制音量图标)
const audioVolume = ref(0.5);
// 音量进度条
const audioProgress = ref(50);
// 监听页面音量
const setPageVolume = (e) => {
  // 获取点击百分比
  const cilckLength = Math.round((e.offsetX * 10) / 70) / 10;
  playAudio.value.volume = cilckLength;
  audioVolume.value = playAudio.value.volume;
  audioProgress.value = playAudio.value.volume * 100;
};
</script>
<style lang='less'>
@import url(../../assets/fonts/player/iconfont.css);
@import url(../../assets/fonts/player-add/iconfont.css);
@import url(../../assets/fonts/player/danqu/iconfont.css);

.app-new-player {
  z-index: 998;
  width: 100%;
  height: 80px;
  background-color: rgb(255, 255, 255);
  position: fixed;
  bottom: 0px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-top: 1px solid rgb(0 0 0 / 13%);
  padding: 0 10px;

  .player-describe {
    display: flex;
    max-width: 200px;

    .player-song-pic {
      position: relative;

      &:hover {
        .pic-shade {
          opacity: 0.6;
        }
      }

      .pic-shade {
        position: absolute;
        top: 0;
        background-color: black;
        opacity: 0;
        display: flex;
        justify-content: center;
        align-items: center;

        i {
          font-size: 30px;
          font-weight: 100;
        }

        &:hover {
          cursor: pointer;
        }
      }

      .pic-shade,
      img {
        width: 45px;
        height: 45px;
        border-radius: 4px;
      }
    }

    .player-name {
      padding-left: 10px;

      .name-song {
        font-size: 15px;
        /* 文字省略 */
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 1;
        -webkit-box-orient: vertical;
        .user-love {
          color: red;
        }

        i {
          font-size: 20px;
          margin-left: 10px;
        }
      }

      .name-singer {
        margin-top: 2px;
        /* 文字省略 */
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 1;
        -webkit-box-orient: vertical;
      }

      .name-singer,
      .name-song {
        &:hover {
          cursor: pointer;
          color: black;
        }
      }
    }
  }

  .player-module {
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    color: black;

    .player-module-operation,
    .player-progress-box {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 450px;
    }
    .player-module-operation {
      padding: 0 100px;
      margin-bottom: 10px;
      i {
        font-size: 18px;

        &:hover {
          cursor: pointer;
          color: #ef6767;
        }
      }
      div {
        margin: 0 15px;
      }

      .module-on-off {
        background-color: #f4f4f4;
        width: 35px;
        height: 35px;
        text-align: center;
        line-height: 35px;
        border-radius: 40px;

        .icon-zanting {
          font-weight: 600;
        }

        &:hover {
          cursor: pointer;
          background-color: #e5e5e5;
        }

        i {
          &:hover {
            color: black;
          }
        }
      }

      .player-up,
      .player-next {
        i {
          font-size: 22px;
        }
      }
      .player-lyrice {
        font-family: "幼圆";
        color: #000000d9;
        font-weight: 600;
        cursor: default;

        &:hover {
          cursor: pointer;
          color: #ef6767;
        }
      }
    }
    .player-progress-box {
      .player-progress {
        margin: 0 6px;
        width: 370px;
        height: 3px;

        &:hover {
          cursor: pointer;
          height: 4.5px;
        }

        .van-progress__portion {
          &:hover {
            cursor: pointer;
          }
        }
      }

      span {
        color: #00000054;
        font-size: 10px;

        &:hover {
          cursor: default;
        }
      }
    }
  }

  .player-addition {
    display: flex;
    align-items: center;

    i {
      color: black;
      font-size: 22px;
    }

    div {
      margin-right: 20px;

      &:hover {
        cursor: pointer;
      }
    }

    .player-tone-quality {
      border: 1px solid;
      border-radius: 3px;
      padding: 0px 3px;
    }

    .player-volume,
    .player-friend {
      transform: scale(1.2);
    }

    .player-volume {
      position: relative;

      &:hover {
        .volume-change {
          display: block;
        }
      }

      .volume-change {
        display: none;
        z-index: 199;
        position: absolute;
        background-color: white;
        width: 30px;
        height: 100px;
        top: -102px;
        left: -7px;
        border-radius: 4px;
        border: 1px solid #00000008;
        box-shadow: 1px 1px 1px #00000021;

        &:hover {
          cursor: default;
        }

        .volume-changer-progress {
          transform: rotate(270deg);
          background: #e6e6e6;
          width: 70px;
          height: 3px;
          right: 20px;
          top: 50px;

          &:hover {
            cursor: pointer;
          }
        }
      }
    }
  }
}
</style>